<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- 通用工具栏组件使用 -->
      <page-tools>
        <!-- 自定义左侧内容 -->
        <template #slot-left>
          <span>共19条记录</span>
        </template>

        <!-- 自定义右侧内容 -->
        <template #slot-right>
          <el-button type="danger" size="small" @click="$router.push('/excel')">导入excel</el-button>
          <el-button type="success" size="small" @click="downloadExcel">导出excel</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="employeesList">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto">
            <template #default="{row}">
              <ImageHolder :src="row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" sortable :sort-method="sortMethodFn" />
          <!-- <el-table-column label="聘用形式">
            <template #default="{row:{formOfEmployment}}">
              <span>{{ formatFormOfEmploymentFn(formOfEmployment) }}</span>
            </template>
          </el-table-column> -->
          <el-table-column prop="formOfEmployment" label="聘用形式" :formatter="formatter" />
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间">
            <template #default="{row:{timeOfEntry}}">
              <span>{{ $dateFormat(timeOfEntry) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id=' + row.id)">查看</el-button>
              <el-button type="text" size="small" @click="addRoleBtnFn(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="del(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <!-- 分页区域 -->
          <el-pagination
            :current-page="query.page"
            :page-sizes="[10, 15, 20, 25]"
            :page-size="query.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
    </div>
    <!-- 新增员工弹框组件 -->
    <el-dialog title="新增员工" :visible.sync="showDialog" @close="closeDialogFn">
      <emp-dialog ref="empForm" :show-dialog.sync="showDialog" :tree-data="treeData" @enterEV="addFn" />
    </el-dialog>
    <!-- 员工-分配角色权限 - 弹窗 -->
    <el-dialog title="分配角色" :visible.sync="showAssignRoleDialog">
      <!-- 设置角色组件 -->
      <assign-role-dialog :role-list="roleList" :role-ids="roleIds" @close="closeFn" @confirm="addRoleFn" />
    </el-dialog>
  </div>
</template>

<script>
import { getEmployeeListAPI, delEmployeeListAPI, addEmployee, getRolesAPI, getUserDetailByIdAPI, assignRolesAPI } from '@/api/index.js'
import empDialog from '@/views/employees/components/empDialog.vue'
import AssignRoleDialog from './components/assignRoleDialog.vue'
import Employees from '@/api/constant/employees'
// 引入api方法
import { departmentsListAPI } from '@/api'
// 树形结构的转换方法
import { transTree } from '@/utils'
export default {
  name: 'Employees',
  components: {
    empDialog,
    AssignRoleDialog
  },
  data() {
    return {
      query: {
        page: 1, // 页码
        size: 10 // 每页条数
      },
      employeesList: [], // 员工列表
      total: 0, // 数据总条数
      showDialog: false, // 添加员工组件的展示
      treeData: [], // 部门列表数据
      showAssignRoleDialog: false, // 分配角色查看显隐
      roleList: [], // 角色列表数据
      roleIds: [], // 现有-角色列表
      userId: ''// 点击的那个员工的id
    }
  },
  // 声明周期方法,没有挂载到this组件对象身上,this.created()是错误的
  created() {
    // 获取员工列表数据
    this.getEmployeeList()
    // 调用获取部门列表的方法
    this.getDepartments()
    // 获取部门列表数据
    this.getRoleListFn()
  },
  methods: {
    // 删除
    async del(id) {
      // console.log(id)
      try {
        await this.$confirm('确认删除吗?', '提示', { type: 'warning' })
        const { success, message } = await delEmployeeListAPI(id)
        if (!success) return this.$message.error(message)
        this.$message.success(message)
        if (this.employeesList.length === 1 && this.query.page > 1) this.query.page--
        this.getEmployeeList()
      } catch (e) {
        this.$message.info('取消删除')
      }
    },
    // 每页显示的条数发生改变时触发
    handleSizeChange(newSize) {
      this.query.size = newSize
      this.query.page = 1
      this.getEmployeeList()
    },

    // 当前页码发生改变时触发
    handleCurrentChange(newPage) {
      this.query.page = newPage
      this.getEmployeeList()
    },

    // 获取员工列表
    async getEmployeeList() {
      const { data: { rows, total }} = await getEmployeeListAPI(this.query)
      this.employeesList = rows
      this.total = total
      // console.log(rows)
    },
    formatFormOfEmploymentFn(num) {
      const obj = {
        1: '正式',
        2: '非正式'
      }
      return obj[num]
    },
    // 格式化表格的某一项
    formatter(row, column, cellValue, index) {
      // 用数组的 find 方法找到 id = 1 的元素，再取出它的 value
      const obj = Employees.hireType.find((item) => Number(item.id) === Number(row.formOfEmployment))
      return obj ? obj.value : '未知'
    },
    // 工号排序
    sortMethodFn(a, b) {
      return a.workNumber - b.workNumber // 字符串相减,会自动转成数字,返回数字
    },
    // 获取树行组件的数据
    async getDepartments() {
      const res = await departmentsListAPI()
      if (!res.success) return this.$message.error(res.message)
      this.treeData = transTree(res.data.depts, '')
      // console.log(this.treeData)
    },
    // 新增员工
    async addFn(data) {
      const res = await addEmployee(data)
      console.log(res)
      this.getEmployeeList()
    },
    // 清空表单
    closeDialogFn() {
      this.$refs.empForm.$refs.addForm.resetFields()
    },
    // 导出 Excel
    downloadExcel() {
      const headerArr = ['序号', '姓名', '头像', '手机号', '工号', '聘用形式', '部门', '入职时间']
      const keyobj = {
        '序号': 'id',
        '姓名': 'username',
        '头像': 'staffPhoto',
        '手机号': 'mobile',
        '工号': 'workNumber',
        '聘用形式': 'formOfEmployment',
        '部门': 'departmentName',
        '入职时间': 'timeOfEntry'
      }
      const valueArr = this.employeesList.map((item, index) => {
        const newArr = []
        headerArr.forEach(key => {
          if (keyobj[key] === 'id') {
            newArr.push(index + 1)
          } else if (keyobj[key] === 'formOfEmployment') {
            const obj = Employees.hireType.find((item) => Number(item.id) === Number(item[keyobj[key]]))
            newArr.push(obj ? obj.value : '未知')
          } else { newArr.push(item[keyobj[key]]) }
        })
        return newArr
      })
      // const newArr = this.employeesList.map(item => Object.values(item))
      import('@/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象
        excel.export_json_to_excel({
          header: headerArr, // 表头 必填
          data: valueArr, // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    // 分配角色->按钮点击事件
    addRoleBtnFn(userId) {
      this.showAssignRoleDialog = true
      this.getUserRoles(userId)
      this.userId = userId
    },
    // 分配角色->确定和取消按钮的点击关闭弹窗
    closeFn() {
      this.showAssignRoleDialog = false
    },
    // 请求-角色列表数据
    async getRoleListFn() {
      const { data: { rows }} = await getRolesAPI()
      // console.log(rows)
      this.roleList = rows
    },
    // 获得现有角色列表(在点击分配角色按钮时触发)
    async getUserRoles(id) {
      const { data: { roleIds }} = await getUserDetailByIdAPI(id)
      this.roleIds = roleIds || []
      // 如果后台发现roleIds没有,就返回null,导致assignRoleDialog的watch里 ...null报错
      // 所以,需要在没有值的时候给一个空数组  ...[] 不会报错
    },
    // 分配角色->确定->调用接口
    async addRoleFn(roleIdArr) {
      const { success, message } = await assignRolesAPI({ id: this.userId, roleIds: roleIdArr })
      // console.log(success, message)
      if (!success) return this.$message.error(message)
      this.$message.success(message)
    }
  }
}
</script>

<style lang="scss" scoped></style>
